import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/widget/common.dart';
import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';
import '../../../../utils/toast_utils.dart';
import '../../../login/model/login_resp.dart';
import '../model/feedback_list_resp.dart';

/// 反馈 页面
class FeedbackSubmitPage extends ConsumerStatefulWidget {
  const FeedbackSubmitPage({super.key});

  @override
  ConsumerState<FeedbackSubmitPage> createState() => _FeedbackSubmitPageState();
}

class _FeedbackSubmitPageState extends ConsumerState<FeedbackSubmitPage>with WidgetsBindingObserver {

  bool showLoading = true;
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _suggestionController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _orderNumberController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _textFieldFocusNode = FocusNode();
  bool _isKeyboardVisible = false;
  bool _contextInitialized = false;

  double bottomoffY = 0;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {

    });
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _textFieldFocusNode.addListener(() {
      print(_textFieldFocusNode.hasFocus);
      if (!_textFieldFocusNode.hasFocus) {
        _hideKeyboard();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _contextInitialized = true;
      _checkKeyboardVisibility();
    });
  }
  _hideKeyboard() {
    // 在这里可以执行你想要的操作
    setState(() {
      bottomoffY = 0;
    });
    _scrollToInputField(bottomoffY);
  }

  @override
  void dispose() {
    _textFieldFocusNode.dispose();
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }
  void _scrollToInputField(double bottomoffY) {
    if (bottomoffY > 0) {
      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }else {
      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.animateTo(
          _scrollController.position.minScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      });
    }

  }
  void _checkKeyboardVisibility() {
    final double bottomInsets = MediaQuery.of(context).viewInsets.bottom;
    XLogger.info(bottomInsets);
    setState(() {
      _isKeyboardVisible = !(bottomInsets > 0);
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    if (_contextInitialized) {
      _checkKeyboardVisibility();
      if (!_isKeyboardVisible) {
        _hideKeyboard();
        // 这里可添加你需要的操作
      }
    }
  }



  Future<void> _toSubmitFeedback() async{
    XLogger.info("_toSubmitFeedback");
    if (!_phoneController.text.isNotEmpty) {
      ToastUtils.showToast('请输入联系电话');
      return ;
    }
    if (!_titleController.text.isNotEmpty) {
      ToastUtils.showToast('请输入标题');
      return ;
    }
    if (!_suggestionController.text.isNotEmpty) {
      ToastUtils.showToast('请输入描述内容');
      return ;
    }
    final deviceInfo = ref.watch(deviceInfoProvider);
    LoginData loginData = SpUtil.getObj('loginData', (v) => LoginData().fromJson(v));

    final queryParams = {
      'imei': deviceInfo.imei,
      'createBy': loginData.userId,
      'contacts': _phoneController.text,
      'subject': _titleController.text,
      'content': _suggestionController.text,
    };

    final res = await post<BaseResp, BaseResp>(
        '$newBaseULr/feedback/add',
        data: queryParams,
        decodeType: BaseResp());
     res.when(success: (resp) {
      if (resp.code == 200) {
        context.pop('更新成功');
        ToastUtils.showToast('反馈成功');
      }
    }, failure: (String msg, int code) {
       ToastUtils.showToast('反馈失败');
     });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('反馈', style: TextStyle(fontSize: 18)),
          centerTitle: true,
          backgroundColor: AppTheme.themeConfig.navBarColor,
          foregroundColor: AppTheme.themeConfig.primaryColor,
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              height: kToolbarHeight,
              padding: const EdgeInsets.only(top: 8),
              alignment: Alignment.center,
              child: const Text(' <返回',
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  style: TextStyle(color: Colors.black)),
            ),
          ),
        ),
        backgroundColor: AppTheme.themeConfig.navBarColor,
      resizeToAvoidBottomInset: false,

      body:


      Stack(
        children: [
          SingleChildScrollView(
            controller: _scrollController,

            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '反馈标题',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                          ),
                        ),
                        const SizedBox(height: 8),
                        SizedBox(
                          height: 60,
                          child: TextField(
                            maxLength: 20,
                            controller: _titleController,
                            decoration: InputDecoration(
                              hintText: '请输入',
                              contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Container(
                          margin: const EdgeInsets.symmetric(horizontal: 5),
                          height: 1,
                          color: Colors.grey,
                        ),
                        const SizedBox(height: 16),
                        const Text(
                          '详细建议',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                          ),
                        ),
                        const SizedBox(height: 8),
                        SizedBox(
                          height: 150,
                          child: TextField(
                            controller: _suggestionController,
                            maxLines: null,
                            maxLength: 100,
                            expands: true,
                            textAlignVertical: TextAlignVertical.top,
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                            ),
                            decoration: InputDecoration(
                              // 使用换行符 \n 让 hintText 展示两行
                              hintText: '请输入10个字以上的问题描述，以便\n我们提供更好的服务',
                              contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              counterText: '${_suggestionController.text.length}/100',
                            ),
                            onChanged: (value) {
                              setState(() {});
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: AppTheme.themeConfig.greyBgColor,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '联系电话',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                          ),
                        ),
                        const SizedBox(height: 8),
                        SizedBox(
                          height: 40,
                          child: TextField(
                            controller: _phoneController,
                            decoration: InputDecoration(
                              hintText: '请输入',
                              contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                            ),

                            inputFormatters: [
                              // 只允许输入数字
                              FilteringTextInputFormatter.allow(RegExp('[0-9]')),
                              // 限制输入为11个数字
                              LengthLimitingTextInputFormatter(11),
                            ],
                            // 数字键盘
                            keyboardType: TextInputType.number,
                            onTap: () {
                              setState(() {
                                bottomoffY = 50;
                              });
                              _scrollToInputField(bottomoffY);
                            },
                            onSubmitted: (string) {
                              FocusScope.of(context).unfocus();

                            },
                            onEditingComplete: () {
                              FocusScope.of(context).unfocus();
                            },
                          ),
                        ),
                        const SizedBox(height: 16),
                        const Text(
                          '订单编号（选填）',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                          ),
                        ),
                        const SizedBox(height: 8),
                        SizedBox(
                          height: 40,
                          child: TextField(
                            maxLines: 25,
                            focusNode: _textFieldFocusNode,
                            controller: _orderNumberController,
                            decoration: InputDecoration(
                              hintText: '请输入',
                              contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(color: Colors.grey),
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                bottomoffY = 300;
                              });
                              _scrollToInputField(bottomoffY);
                            },
                            onSubmitted: (string) {

                              FocusScope.of(context).unfocus();

                            },
                            onEditingComplete: () {
                              FocusScope.of(context).unfocus();

                            },
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            _toSubmitFeedback();
                          },
                          child: Container(
                            alignment: Alignment.center,
                            width: MediaQuery.of(context).size.width,
                            margin:
                            const EdgeInsets.only(left: 30, right: 30, top: 10, bottom: 16),
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            decoration: BoxDecoration(
                                color: AppTheme.themeConfig.primaryColor,
                                borderRadius: BorderRadius.circular(20)),
                            child: lpText(
                                "提交",
                                color: Colors.white,
                                size: 16),
                          ),
                        ),

                      ],
                    ),
                  ),
                  Container(
                    color: AppTheme.themeConfig.navBarColor,
                    height: bottomoffY,
                  ),
                ],
              ),
            ),
          ),

        ],
      ),




    );
  }
}
